/*获取订单号*/
var returnOrderId = sessionStorage.getItem("returnOrderId");
var returnId = sessionStorage.getItem("returnId");
var loginData = JSON.parse(web.readCookie("loginData"));
var customerId = ""
var customerCode = ""
var orderDetail = ""
var townCode = "";
var town = "";
$(".notui").attr("onclick", "return false;");
$(".notui").css({"color": "grey"});
function initCity(special, aa, bb) {
    var user_data = {
        level: '102',
        parentCode: special
    }
    var succCallBack = function (data, status, response) {

        if (data.errorCode == "0") {
            var tab_data = data.list;
            if (tab_data == '') {
                cer += '<option value=""></option>'
                $("#getCitys").html(cer);
            } else {
                var cer = '<option value="' + aa + '">' + bb + '</option>'
                for (var i = 0; i < tab_data.length; i++) {
                    cer += '<option value="' + tab_data[i].code + '">' + tab_data[i].name + '</option>'
                }
                $("#getCitys").html(cer);
            }
        }
    };
    web.doAjax(root.publics.pcgetLowerAddress, 'post', user_data, succCallBack);

}
function initarea(special, aa, bb) {
    user_data = {
        level: '103',
        parentCode: special
    }
    var succCallBack = function (data, status, response) {
        if (data.errorCode == "0") {
            var tab_data = data.list;
            if (tab_data == '') {
                cer += '<option value=""></option>'
                $("#getAreas").html(cer);
            } else {
                var cer = '<option value="' + aa + '">' + bb + '</option>'
                for (var i = 0; i < tab_data.length; i++) {
                    cer += '<option value="' + tab_data[i].code + '">' + tab_data[i].name + '</option>'
                }
                $("#getAreas").html(cer);
            }
        }
    };
    web.doAjax(root.publics.pcgetLowerAddress, 'post', user_data, succCallBack);
}
/*获取收货区域*/
discountdatas(123)
function discountdatas(val) {
    if (val == 123) {
        //初始化 省
        var user_data = {
            level: '101',
        }
        var succCallBack = function (data, status, response) {
            if (data.errorCode == "0") {
                var tab_data = data.list;
                if (tab_data == '') {
                    cer += '<option value=""></option>'
                    $("#getProvinces").html(cer);
                } else {
                    var cer = "<option value=''>请选择收货区域</option>"
                    for (var i = 0; i < tab_data.length; i++) {
                        cer += '<option value="' + tab_data[i].code + '">' + tab_data[i].name + '</option>'
                    }
                    $("#getProvinces").html(cer);
                }
            }
        };
        web.doAjax(root.publics.pcgetLowerAddress, 'post', user_data, succCallBack);
    } else if (val == 1) {
        //市
        var cer5 = "<option value=''>请选择收货区域</option>"
        $("#getAreas").html(cer5);
        $("#getCountys").html(cer5);
        var special = $('#getProvinces').val()
        if (special == "") {
            var cer = "<option value=''>请选择收货区域</option>"
            $("#getCitys").html(cer);
        } else {
            var user_data = {
                level: '102',
                parentCode: special
            }
            var succCallBack = function (data, status, response) {
                if (data.errorCode == "0") {
                    var tab_data = data.list;
                    if (tab_data == '') {
                        cer += '<option value=""></option>'
                        $("#getCitys").html(cer);
                    } else {
                        var cer = "<option value=''>请选择收货区域</option>"
                        for (var i = 0; i < tab_data.length; i++) {
                            cer += '<option value="' + tab_data[i].code + '">' + tab_data[i].name + '</option>'
                        }
                        $("#getCitys").html(cer);
                    }
                }
            };
            web.doAjax(root.publics.pcgetLowerAddress, 'post', user_data, succCallBack);
        }

    } else if (val == 2) {
        //区
        var special = $('#getCitys').val()
        if (special == "") {
            var cer = "<option value=''>请选择收货区域</option>"
            $("#getAreas").html(cer);
        } else {
            var user_data = {
                level: '103',
                parentCode: special
            }
            var succCallBack = function (data, status, response) {
                if (data.errorCode == "0") {
                    var tab_data = data.list;
                    if (tab_data == '') {
                        cer += '<option value=""></option>'
                        $("#getAreas").html(cer);
                    } else {
                        var cer = "<option value=''>请选择收货区域</option>"
                        for (var i = 0; i < tab_data.length; i++) {
                            cer += '<option value="' + tab_data[i].code + '">' + tab_data[i].name + '</option>'
                        }
                        $("#getAreas").html(cer);
                    }
                }
            };
            web.doAjax(root.publics.pcgetLowerAddress, 'post', user_data, succCallBack);
        }
    } else if (val == 3) {
        //县
        var special = $('#getAreas').val()
        if (special == "") {
            var cer = "<option value=''>请选择收货区域</option>"
            $("#getCountys").html(cer);
        } else {
            var user_data = {
                level: '104',
                parentCode: special
            }
            var succCallBack = function (data, status, response) {
                if (data.errorCode == "0") {
                    var tab_data = data.list;
                    if (tab_data == '') {
                        cer += '<option value=""></option>'
                        $("#getCountys").html(cer);
                    } else {
                        var cer = "<option value=''>请选择收货区域</option>"
                        for (var i = 0; i < tab_data.length; i++) {
                            cer += '<option value="' + tab_data[i].code + '">' + tab_data[i].name + '</option>'
                        }
                        $("#getCountys").html(cer);
                    }
                }
            };
            web.doAjax(root.publics.pcgetLowerAddress, 'post', user_data, succCallBack);
        }
    }
}
window.onload = function () {
    /*通过订单号获取订单详情*/
    $.ajax({
        type: "POST",
        url: root.orderInter.order_queryRefundOrderDetails,
        cache: false,  //禁用缓存F
        dataType: "json",
        data: {
            "order_id": returnOrderId,// 订单编号
            "refund_id": returnId // 退货单编号
        },
        success: function (result) {
            orderDetail = result
            if (result.orderRefund.refund_status == "10") {
                $("#passCheck").show();
                $("#rejectCheck").show();
            } else if (result.orderRefund.refund_status == "20") {
                $("#detailCancel").show();
            }
            if (result.orderRefund.refund_status == "40" && result.orderRefund.is_refund_abnormal == 1) {
                $("#rejectCheck").show();
            }
            sessionStorage.setItem("returnOrderDetail", JSON.stringify(result));
            $.ajax({
                type: "POST",
                url: root.dockingplatform.queryPreOrderDetail,
                cache: false, //禁用缓存
                dataType: "json",
                data: {
                    "orderId": returnOrderId, // 订单编号
                },
                success: function (results) {
                    customerCode = results.data.parent_customer_code;
                    renderOrderPage(result, customerCode);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest);
                }
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}
function getOrderDetail() {
    var params = {
        order_id: returnOrderId,// 订单编号
        refund_id: returnId // 退货单编号
    }
    var successData = function (data) {
        if (data.errorCode == 0) {
            orderDetail = data;
            if (data.orderRefund.refund_status == 10) {
                $("#passCheck").show();
                $("#rejectCheck").show();
            } else if (data.orderRefund.refund_status == 20) {
                $("#detailCancel").show();
            }
            sessionStorage.setItem("returnOrderDetail", JSON.stringify(data));
            renderOrderPage(data);
        } else {
            layer.msg(data.msg, {time: 2000})
        }
    }
    return web.doAjax(root.orderInter.order_queryRefundOrderDetails, 'post', params, successData)
}
function detailCancel() {
    layer_show("取消订单", "returnCancleAlert.html", "600", "300");
}
var stopRejectCheck = true;
function rejectCheck() {
    if (stopRejectCheck == true) {
        layer_show("审核驳回", "rejectionRemark.html", "600", "300");
    }
}
function passCheck() {
    var orderidallall = ""
    layer.confirm('审核通过？', function (index) {
        stopRejectCheck = false;
        if ($('#refundDesc').val() == "") {
            showMsg(5, '请输入必填信息');
            stopRejectCheck = true;
            return false;
        }
        if ($('#returnReason').val() == "0") {
            showMsg(5, '请选择退货原因');
            stopRejectCheck = true;
            return false;
        }

        if ($('#refundDesc').val() == "" || $("#returnsReason").val() == "" || $("#getProvinces").val() == "" || $("#getCitys").val() == "" || $("#detail_address").val() == "" || $("#received_name").val() == "" || $("#received_telephone").val() == "" || $("#getCountys option:selected").html() == "请选择收货区域") {
            showMsg(5, '请输入必填信息');
            stopRejectCheck = true;
            return false;
        }
        if ($("#returnsReason").val() == 10) {
            if ($("#orderidall").html() == "") {
                showMsg(5, '请关联下次送货订单号');
                stopRejectCheck = true;
                return false;
            }
            orderidallall = $("#orderidall").html()
        } else {
            orderidallall = ""
        }

        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: root.orderInter.order_unaudit_auditAgree,
            cache: false, //禁用缓存
            dataType: "json",
            data: JSON.stringify({
                refund_id: returnId,
                audit_person_id: loginData.user.user_ID,
                audit_person_name: loginData.user.name,
                refund_desc: $('#refundDesc').val(),
                return_fare_flag: isSetReturnFreight,
                service_fee: $('#serviceMoneyInput').val(),
                shipping_fee: $('#deliveryMoneyInput').val(),
                refund_reason: $("#returnReason").val(),
                "take_goods_type": $("#returnsReason").val(),
                "province": $("#getProvinces").val(),//省id
                "province_name": $("#getProvinces option:selected").html(),//省名称
                "city": $("#getCitys").val(),
                "city_name": $("#getCitys option:selected").html(),
                "area": $("#getAreas").val(),
                "area_name": $("#getAreas option:selected").html(),
                "detail_address": $("#detail_address").val(),
                "received_name": $("#received_name").val(),
                "received_telephone": $("#received_telephone").val(),
                "relatedOrderId": orderidallall,
                "town": $("#getCountys").val(),
                "town_name": $("#getCountys option:selected").html(),
                "lng": $("#lng").val(),
                "lat": $("#lat").val(),
            }), //传入组装的参数
            success: function (result) {
                if (result.code == 0) {
                    var data = result.data;
                    if (data) {
                        layer.msg(data, {icon: 6, time: 3000});
                    } else {
                        showMsg(6, "审核成功");
                    }

                    setTimeout(function () {
                            window.location.reload()
                        }, 1000
                    )
                } else if (result.code == 2) {
                    stopRejectCheck = true;
                    showMsg(5, '请输入必填信息');
                } else {
                    showMsg(5, result.message);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("error:" + XMLHttpRequest);
            }
        });
        layer.msg('已审核', {
            icon: 6,
            time: 1000
        });
    });
}
function showMsg(icon, msg) {
    layer.msg(msg, {
        icon: icon,
        time: 1000
    });
}
function changeOrderState(orderState, customerId) {
    $("#affirmMoney").siblings().css({
        display: "none"
    });
    switch (orderState) {
        /*订单状态*/
        case 10:
            $('#confirmInfo').hide();
            $("#relatedDocumentsbtu").show();
            return "待审核";
        case 30:
            if (customerCode != 'D000000051' && customerCode != 'D000000022' && customerCode != 'D000000018') {
                $("#detailCancel").show();
            }
            $('#refundDesc').attr('disabled', true)
            $("#passCheck").hide();
            $("#rejectCheck").hide();
            return "退货处理";
        case 40:
            $("#detailCancel").hide();
            $("#passCheck").hide();
            return "退款处理";
        case 50:

            $('#refundDesc').attr('disabled', true);
            return "已完成";
        case 60:
            $("#refundInfo").hide();
            $('#closeInfo').show();
            $('#refundDesc').attr('disabled', true);
            $("#passCheck").hide();
            $("#rejectCheck").hide();
            $('#detailCancel').hide();
            return "已关闭";
    }
}
/*datatable*/
var dataSource = new Array();
//table的数据源
var table; //table对象
dataSource = [];
function renderOrderPage(data, customerCode) {
    if (data.orderExt != null && data.orderExt != "") {
        $("#lng").val(data.orderExt.lng)
        $("#lat").val(data.orderExt.lat)
    }
    // /*转换状态*/
    customerId = data.orderRefund.customer_id
    var order_status = changeOrderState(data.orderRefund.refund_status, customerCode);
    $("#orderState").html(order_status);
    /*基本信息*/
    $("#askFor-code").html(data.orderRefund.refund_id);
    $("#order-code").html(data.orderRefund.order_id);
    $("#sales-manager").html(data.orderRefund.sales_manager_name);
    // 异常提醒展示 orderRefund 里面的 is_refund_abnormal   是否退单异常：0=否；1=是
    data.orderRefund.is_refund_abnormal == 1 ? $('#errorTip').show() : $('#errorTip').hide();
    //下次送货订单号
    $("#orderidall").html(data.orderRefund.related_order_id)
    if (data.orderRefund.refund_sorce == 10) {
        $('#return-type').html('拒收')
        $(".returnGoods").hide();
    }
    if (data.orderRefund.refund_sorce == 20) {
        $('#return-type').html('退货')
        $(".returnGoods").css({
            display: "table-cell"
        });
    }
    if (data.orderRefund.refund_sorce == 11) {
        $(".returnGoods").hide();
        $('#return-type').html('拒收-拦截')
    }
    /*关闭信息*/
    if (data.orderRefund.close_role == 10) {
        $("#operator").html(data.orderRefund.customer_name);
    } else {
        $("#operator").html('客服');
    }
    if (data.orderRefund.refund_status == 10) {
        $("#relationButton").css({
            display: "inline"
        });
    } else {
        $("#relationButton").hide();
    }
    //下次送货订单号
    $("#orderidall").html(data.orderRefund.related_order_id)
    if (data.orderRefund.refund_status == 10) { //上门取货
        if (data.orderRefund.take_goods_type == 10) {
            $("#returnsReason").val(data.orderRefund.take_goods_type)
            if (customerCode == 'D000000022') {
                $("#returnsReason").attr("disabled", "disabled")
            }
            var townname = ""
            if (data.orderRefund.town_name != null) {
                townname = data.orderRefund.town_name
            } else {
                townname = ""
            }
            $("#getProvinces option:selected").val("")
            $("#getProvinces option:selected").html("请选择收货区域")
            $("#getProvinces").attr("disabled", false)

            $("#getCitys option:selected").val("")
            $("#getCitys option:selected").html("请选择收货区域")
            $("#getCitys").attr("disabled", false)

            $("#getAreas option:selected").val("")
            $("#getAreas option:selected").html("请选择收货区域")
            $("#getAreas").attr("disabled", false)

            $("#getCountys option:selected").val("")
            $("#getCountys option:selected").html("请选择收货区域")
            $("#getCountys").attr("disabled", false)
            // sss1(returnOrderId);
            if (townname == "" || townname == null) {
                townname = orderDetail.orderExt.receiver_town_name;
            }
            $("#detail_address").val(data.orderRefund.province_name + "" + data.orderRefund.city_name + "" + data.orderRefund.area_name + "" + townname + "" + data.orderRefund.detail_address);
            $("#detail_address").attr("disabled", false)

            $("#received_name").val(data.orderRefund.received_name)
            $("#received_name").attr("disabled", false)

            $("#received_telephone").val(data.orderRefund.received_telephone)
            $("#received_telephone").attr("disabled", false)
        } else {
            returnsReasonall()
        }
    } else {
        $("#returnsReason").val(data.orderRefund.take_goods_type);
        $("#returnsReason").attr("disabled", "disabled")
        $("#getProvinces option:selected").val(data.orderRefund.province)
        $("#getProvinces option:selected").html(data.orderRefund.province_name)
        $("#getProvinces").attr("disabled", "disabled")

        $("#getCitys option:selected").val(data.orderRefund.city)
        $("#getCitys option:selected").html(data.orderRefund.city_name)
        $("#getCitys").attr("disabled", "disabled")

        $("#getAreas option:selected").val(data.orderRefund.area)
        $("#getAreas option:selected").html(data.orderRefund.area_name)
        $("#getAreas").attr("disabled", "disabled")

        if (data.orderRefund.town == "" || data.orderRefund.town == null) {
            //（新增）通过三级地址和详细地址查询出四级地址
            queryDetailAddress(returnOrderId);
        } else {
            $("#getCountys option:selected").val(data.orderRefund.town)
            $("#getCountys option:selected").html(data.orderRefund.town_name)
            $("#getCountys").attr("disabled", "disabled")
        }
        $("#detail_address").val(data.orderRefund.detail_address);
        $("#detail_address").attr("disabled", "disabled")

        $("#received_name").val(data.orderRefund.received_name)
        $("#received_name").attr("disabled", "disabled")

        $("#received_telephone").val(data.orderRefund.received_telephone)
        $("#received_telephone").attr("disabled", "disabled")
    }
    //是否展示下次送货订单号
    displayornot()
    /*退货申请信息*/
    $('#qreturn-reason').html(reason2(data.orderRefund.customer_refund_reason))//前台退货原因
    $('#return-reason').html(reason(data.orderRefund.refund_reason))
    if (data.orderRefund.refund_reason == 60) {
        $('#returnReason').val("50")
    } else {
        $('#returnReason').val(data.orderRefund.refund_reason)
    }
    $("#refund-info").html(data.orderRefund.return_desc);
    var townname = ""
    if (data.orderRefund.town_name != null) {
        townname = data.orderRefund.town_name
    } else {
        townname = ""
    }
    if (townname == "" || townname == null) {
        townname = orderDetail.orderExt.receiver_town_name;
    }
    if (data.orderRefund.take_goods_type == 10) {
        $("#get-address-name").html('取货地址：');
        // $("#get-type").html('上门取货');
        $("#returnsReason").val(data.orderRefund.take_goods_type);
        if (customerCode == 'D000000022') {
            $("#returnsReason").attr("disabled", "disabled")
        }
        $('#get-address').html(data.orderRefund.province_name + "" + data.orderRefund.city_name + "" + data.orderRefund.area_name + "" + townname + "" + data.orderRefund.detail_address);

    }
    if (data.orderRefund.take_goods_type == 20) {
        $("#get-address-name").html('邮寄地址：');
        // $("#get-type").html('客户邮寄');
        $("#returnsReason").val(data.orderRefund.take_goods_type);
        if (customerCode == 'D000000022') {
            $("#returnsReason").attr("disabled", "disabled")
        }
        $("#get-address").html(data.orderRefund.province_name + "" + data.orderRefund.city_name + "" + data.orderRefund.area_name + "" + data.orderRefund.detail_address);
    }
    if (data.orderRefund.take_goods_type == 30) {
        $("#get-address-name").html('取货地址：');
        $("#returnsReason").val(data.orderRefund.take_goods_type);
        if (customerCode == 'D000000022') {
            $("#returnsReason").attr("disabled", "disabled")
        }
        $('#get-address').html(data.orderRefund.province_name + "" + data.orderRefund.city_name + "" + data.orderRefund.area_name + "" + townname + "" + data.orderRefund.detail_address);
    }
    $("#askFor-time").html(data.orderRefund.created_at);
    $("#askFor-operator").html(data.orderRefund.customer_name);
    for (var i in data.operateRemarkList) {
        if (data.operateRemarkList[i].operate_type == 10) //审核操作信息
        {
            $('#audit-time').html(data.operateRemarkList[i].created_at);
            $('#auditor').html(data.operateRemarkList[i].operate_username);
            $('#audit-desc').html(data.operateRemarkList[i].refund_remark);
        } else if (data.operateRemarkList[i].operate_type == 20) /*审核驳回信息*/ {
            $('#check').html('审核驳回信息');
            $('#audit-time').html(data.operateRemarkList[i].created_at);
            $('#auditor').html(data.operateRemarkList[i].operate_username);
            $('#audit-desc').html(data.operateRemarkList[i].refund_remark);
            $('#closeInfo').hide();
        }
        if (data.operateRemarkList[i].operate_type == 30) /*已受理取消信息*/ {
            $('#close-time').html(data.operateRemarkList[i].created_at);
            $('#operator').html(data.operateRemarkList[i].operate_username);
            $('#close-intordoce').html(data.operateRemarkList[i].refund_remark);
        }
        if (data.operateRemarkList[i].operate_type == 40) /*退货处理取消*/ {
            $('#close-time').html(data.operateRemarkList[i].created_at);
            $('#operator').html(data.operateRemarkList[i].operate_username);
            $('#close-intordoce').html(data.operateRemarkList[i].refund_remark);
        }
        if (data.operateRemarkList[i].operate_type == 50) /*退款处理取消*/ {
            $('#close-time').html(data.operateRemarkList[i].created_at);
            $('#operator').html(data.operateRemarkList[i].operate_username);
            $('#close-intordoce').html(data.operateRemarkList[i].refund_remark);
        }
        if (data.operateRemarkList[i].operate_type == 100) /*前台客户取消*/ {
            $('#close-time').html(data.operateRemarkList[i].created_at);
            $('#operator').html(data.operateRemarkList[i].operate_username);
            $('#close-intordoce').html(data.operateRemarkList[i].refund_remark);
        }
    }

    /*退款信息*/
    $('#deliveryMoney').html((data.orderRefund.shipping_fee).toFixed(2));//运费
    $('#serviceMoney').html((data.orderRefund.service_fee).toFixed(2));//服务费
    $('#refunded_freight').html((data.orderRefund.refund_amount_final).toFixed(2));//退款金额
    if (data.orderRefund.refund_status != 10) {
        $('.tui').hide();
        $('.notui').hide();
        if (data.orderRefund.return_shipping_flag == 10) {
            $('#return_freight').html((data.orderRefund.shipping_fee).toFixed(2));//退运费
        }
    }
    $('#returnMoney').html((data.refund_amount_final).toFixed(2));


    $('#return-askFor-time').html('无数据');
    $('#return-finish-time').html('无数据');
    //退货商品金额
    $('#returnSkuMoney').html((data.return_product_amount - data.refund_special_promotion_value).toFixed(2));
    var usedpoints = 0//积分分摊
    for (var i = 0; i < data.listBaseAndRefund.length; i++) {
        usedpoints += data.listBaseAndRefund[i].used_points
    }
    $('#shipping_fee').html((data.return_shipping_fee).toFixed(2));
    $('#return_freight').html(0); // 退运费金额
    if (!data.is_returnable_freight) {
        $(".return_freight").attr("onclick", "return false;");
        $(".return_freight").css({"color": "grey", "opacity": "0.6"});
    }
    $('#refundDesc').val(data.orderRefund.refund_desc);
    /*备注*/
    if (data.orderRefundRemark != null) {
        $('#remark').val(data.orderRefundRemark.refund_remark);
    }
    /*凭证信息*/
    for (var i in data.refundProofList) {
        $('#proofPics').append(' <img src="' + data.refundProofList[i].pic_url + '" style="width:100px;height:100px"' +
            ' onclick="setSize(this)"' +
            ' title="点击放大">')
    }
    /*商品信息*/
    if(data.subRefundShowFlag){
        // 展示子订单
        renderSubDataTable(data.subSplitRefundDetailList)
    }else{
        // 展示主订单
        renderListBaseAndRefund(data.listBaseAndRefund);
        $('#datatable').show();
    }
}
// 封装表格
function renderListBaseAndRefund(data,type){
    dataSource.splice(0, dataSource.length); //清空数组
    $.each(data, function (i, field) {
        var rowData = [];
        rowData.push(field.product_pic);//0
        rowData.push(field.parent_warehouse_id);//1
        rowData.push(field.buyyer_count);//2
        rowData.push(field.delivery_count);//3
        rowData.push(field.receive_count);//4
        rowData.push(field.refund_count);//5
        rowData.push(field.sku_code);//6
        rowData.push(field.product_name);//7
        rowData.push(field.sku_info);//8
        rowData.push(field.unit_name);//9
        rowData.push(field.sku_id);//10
        rowData.push(field.color);//11
        rowData.push(field.sale_price);//12
        rowData.push(field.activity_type);//13
        rowData.push(field.promotion_value);//14
        rowData.push(field.final_refund_count);//实退数量 15
        rowData.push(field.final_refund_price);//实退单价16
        rowData.push(field.shipping_fee);//实退运费17
        rowData.push(field.final_refund_total);//实退总金额18
        rowData.push(field.refund_status);// 19 商品退货状态 10=>待审核;20=>已受理;30=>退货处理;40=>退款处理;50=>已完成;60=>已关闭
        rowData.push(field.refund_id);// 20 商品退回id
        dataSource.push(rowData);
    });
    if(type!=undefined){
        /*console.log('zidingdan')*/
        initSubDataTable(dataSource,type);
    }else{
       /* console.log('zhudingdan')*/
        initDataTable(dataSource);
    }

}
//---主订单有分页
function initDataTable(dataSource) {
    var dttable = $('#datatable').dataTable(); // 初始化dataTable，清空上一个值
    dttable.fnClearTable(); //清空一下table
    dttable.fnDestroy(); //还原初始化了的datatable
    $("#datatable").DataTable({
        "autoWidth": false,
        "ordering": true,
        "searching": true,
        "paging": true,
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": true,
        "aLengthMenu": [5, 10, 25, 50],
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sZeroRecords": "没有检索到数据",
            "sProcessing": "<img src='./loading.gif' />"
        },
        data: dataSource,
        columnDefs: [{
            "visible": true,
            "targets": 0
        },
            {
                "render": function (data, type, row) {
                    var val = '<div onclick="goToGoodsDetail(\'Code详情\',\'../../goods/sku-info.html\',' + row[10] + ')"' +
                        ' style="cursor:pointer;"><img' +
                        ' style="float:left;width:55px;height:55px;position:relative;top:10px;left:20px"' +
                        ' name=""src="' + row[0] + '" alt=""><div style="float: left;width:180px;padding-top:' +
                        ' 7px;margin-left: 28px;"><div>' + row[6] + '</div><div>' + row[7] + '</div><div>' + row[11] + '</div><div>' + row[8] + '</div></div></div>';
                    return val;
                },
                "targets": 0
            },
            {
                "render": function (data, type, row) {
                    var warehouses = JSON.parse(sessionStorage.getItem("warehouses"))
                    var ss = ""
                    $.each(warehouses.data, function (k, s) {
                        if (row[1] == s.warehouseCode) {
                            ss = s.warehouseName
                        }
                    })
                    return '<span>' + ss + '</span>';
                },
                "targets": 1
            },
            {
                "render": function (data, type, row) {
                    var price = row[12]
                    /*var specialPrice=""
                    if(row[13] == 10){
                        specialPrice=row[14]/row[2]
                    }
                    price=(price-specialPrice).toFixed(2)*/
                    var val = '<span>' + price.toFixed(2) + '元/' + row[9] + '</span>'
                    return val;

                },
                "targets": 2
            },
            {
                "render": function (data, type, row) {
                    if (row[9] != null) {
                        return '<span>' + row[2] + '' + row[9] + '</span>';
                    } else {
                        return '<span>' + row[2] + '</span>';
                    }

                },
                "targets": 3
            },
            {
                "render": function (data, type, row) {
                    if (row[9] != null) {
                        return '<span>' + row[3] + '' + row[9] + '</span>';
                    } else {
                        return '<span>' + row[3] + '</span>';
                    }

                },
                "targets": 4
            },
            {
                "render": function (data, type, row) {
                    if (row[9] != null) {
                        return '<span>' + row[4] + '' + row[9] + '</span>';
                    } else {
                        return '<span>' + row[4] + '</span>';
                    }

                },
                "targets": 5
            },
            {
                "render": function (data, type, row) {
                    return '<span>' + row[5] + '</span>'
                },
                "targets": 6
            },
            /*实退数量*/
            {
                "render": function (data, type, row) {
                    return '<span>' + row[15] + '' + row[9] + '</span>';
                },
                "targets": 7
            },
            /*实退商品单价*/
            {
                "render": function (data, type, row) {
                    return '<span>' + row[16].toFixed(2) + '元/' + row[9] + '</span>';
                },
                "targets": 8
            },
            /*实退商品金额*/
            {
                "render": function (data, type, row) {
                    var productNum = Number(row[15]);// 商品数量
                    var productPrice = Number(row[16]);// 商品单价
                    return '<span>' + (productNum * productPrice).toFixed(2) + ' 元/' + row[9] + '</span>'
                },
                "targets": 9
            },
            /*状态*/
            {
                "render": function (data, type, row) {
                    switch (row[19]) {
                        case 10 :
                            return '待审核';
                        case 20:
                            return '已受理';
                        case 30:
                            return '退货处理';
                        case 40:
                            return '退款处理';
                        case 50:
                            return '已完成';
                        case 60:
                            return '已关闭';
                        default:
                            return ''
                    }
                },
                "targets": 10
            },
            /*操作*/
            {
                "render": function (data, type, row) {
                    var skuCodeAry = [];
                    skuCodeAry.push(row[6]);
                    if (row[19] == 10 || row[19] == 30) {
                        return "<span style='color: #0a60d6;cursor: pointer' onclick='closeOrder(" + JSON.stringify(skuCodeAry) + ")'>关闭</span>"
                    } else {
                        return '<span style="color: #0a60d6"></span>'
                    }
                },
                "targets": 11
            },
        ]
    });
}
// 退货状态
var refundStatus = {
    10:'待审核',
    20:'已受理',
    30:'退货处理',
    40:'退款处理',
    50:'已完成',
    60:'已关闭'
}
function renderSubDataTable(data) {
    var str = '';
    if (data.length > 0) {
        $.each(data, function (index, item) {
            str ='<div class="pd-20 mb-20">\n' +
                '                    <span>售后单号: <span>' + item.refundId + '</span></span>\n' +
                '                    &nbsp; &nbsp;\n' +
                '                    <span>状态: <span>' + refundStatus[item.refundStatus] + '</span></span>\n' +
                '                    &nbsp; &nbsp;\n' +
                '                    <span>原订单号: <span>' + item.orderId + '</span></span>\n' +
                '                    <table class="table table-border table-bordered table-hover table-bg table-sort mt-10 subDatatable'+index+'">' +
                '                        <thead>\n' +
                '                        <tr class="text-c">\n' +
                '                            <th style="width: 300px;">商品</th>\n' +
                '                            <th>发货仓</th>\n' +
                '                            <th>单价</th>\n' +
                '                            <th>购买数量</th>\n' +
                '                            <th>出库数量</th>\n' +
                '                            <th>收货数量</th>\n' +
                '                            <th>申请退货数量</th>\n' +
                '                            <th>实退数量</th>\n' +
                '                            <th>实退商品单价</th>\n' +
                '                            <th>实退商品金额</th>\n' +
                '                            <th>状态</th>\n' +
                '                            <th>操作</th>\n' +
                '                        </tr>\n' +
                '                        </thead>\n' +
                '                        <tbody class="subBody">\n' +
                '                        </tbody>\n' +
                '                    </table>\n' +
                '                </div>';
            $('#subOrderTable').append(str);
            renderListBaseAndRefund(item.splitRefundList, index);
        });

    }
}
function initSubDataTable(data,type){
    var dataTable = $('.subDatatable'+type+'').dataTable();
    dataTable.fnClearTable(); //清空一下table
    dataTable.fnDestroy(); //还原初始化了的datatable*/
    $('.subDatatable'+type+'').DataTable({
        "autoWidth": false,
        "ordering": false,
        "searching": false,
        "paging": false,
        "retrieve": true,
        "destroy": true,
        "bAutoWidth": true,
        "bLengthChange": false,
        "aLengthMenu": false,
        "oLanguage": {
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "抱歉， 没有找到",
            "sInfo": "从 _START_ 到 _END_ /共 _TOTAL_ 条数据",
            "sInfoEmpty": "没有数据",
            "sInfoFiltered": "(从 _MAX_ 条数据中检索)",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "前一页",
                "sNext": "后一页",
                "sLast": "尾页"
            },
            "sProcessing": "<img src='./loading.gif' />"
        },
        data: data,
        columnDefs: [{
            "visible": true,
            "targets": 0
        },
            {
                "render": function (data, type, row) {
                    var val = '<div onclick="goToGoodsDetail(\'Code详情\',\'../../goods/sku-info.html\',' + row[10] + ')"' +
                        ' style="cursor:pointer;"><img' +
                        ' style="float:left;width:55px;height:55px;position:relative;top:10px;left:20px"' +
                        ' name=""src="' + row[0] + '" alt=""><div style="float: left;width:180px;padding-top:' +
                        ' 7px;margin-left: 28px;"><div>' + row[6] + '</div><div>' + row[7] + '</div><div>' + row[11] + '</div><div>' + row[8] + '</div></div></div>';
                    return val;
                },
                "targets": 0
            },
            {
                "render": function (data, type, row) {
                    var warehouses = JSON.parse(sessionStorage.getItem("warehouses"))
                    var ss = ""
                    $.each(warehouses.data, function (k, s) {
                        if (row[1] == s.warehouseCode) {
                            ss = s.warehouseName
                        }
                    })
                    return '<span>' + ss + '</span>';
                },
                "targets": 1
            },
            {
                "render": function (data, type, row) {
                    var price = row[12]
                    return '<span>' + price.toFixed(2) + '元/' + row[9] + '</span>';

                },
                "targets": 2
            },
            {
                "render": function (data, type, row) {
                    if (row[9] != null) {
                        return '<span>' + row[2] + '' + row[9] + '</span>';
                    } else {
                        return '<span>' + row[2] + '</span>';
                    }

                },
                "targets": 3
            },
            {
                "render": function (data, type, row) {
                    if (row[9] != null) {
                        return '<span>' + row[3] + '' + row[9] + '</span>';
                    } else {
                        return '<span>' + row[3] + '</span>';
                    }

                },
                "targets": 4
            },
            {
                "render": function (data, type, row) {
                    if (row[9] != null) {
                        return '<span>' + row[4] + '' + row[9] + '</span>';
                    } else {
                        return '<span>' + row[4] + '</span>';
                    }

                },
                "targets": 5
            },
            {
                "render": function (data, type, row) {
                    return '<span>' + row[5] + '</span>'
                },
                "targets": 6
            },
            /*实退数量*/
            {
                "render": function (data, type, row) {
                    return '<span>' + row[15] + '' + row[9] + '</span>';
                },
                "targets": 7
            },
            /*实退商品单价*/
            {
                "render": function (data, type, row) {
                    return '<span>' + row[16].toFixed(2) + '元/' + row[9] + '</span>';
                },
                "targets": 8
            },
            /*实退商品金额*/
            {
                "render": function (data, type, row) {
                    var productNum = Number(row[15]);// 商品数量
                    var productPrice = Number(row[16]);// 商品单价
                    return '<span>' + (productNum * productPrice).toFixed(2) + ' 元/' + row[9] + '</span>'
                },
                "targets": 9
            },
            /*状态*/
            {
                "render": function (data, type, row) {
                    switch (row[19]) {
                        case 10 :
                            return '待审核';
                        case 20:
                            return '已受理';
                        case 30:
                            return '退货处理';
                        case 40:
                            return '退款处理';
                        case 50:
                            return '已完成';
                        case 60:
                            return '已关闭';
                        default:
                            return ''
                    }
                },
                "targets": 10
            },
            /*操作*/
            {
                "render": function (data, type, row) {
                    var skuCodeAry = [];
                    skuCodeAry.push(row[6]);
                    if (row[19] == 10 || row[19] == 30) {
                        return "<span style='color: #0a60d6;cursor: pointer' onclick='closeOrder(" + JSON.stringify(skuCodeAry) + ")'>关闭</span>"
                    } else {
                        return '<span style="color: #0a60d6"></span>'
                    }
                },
                "targets": 11
            },
        ]
    });
}
// 订单关闭操作
function closeOrder(skuCode) {
    var params = {
        operate_userid: loginData.user.user_ID,
        operate_username: loginData.user.name,
        refund_id: $('#askFor-code').html(),
        skuCodes: skuCode
    }
    var successData = function (data) {
        if (data.code == 0) {
            // 刷新列表
            layer.msg('操作成功！', {time: 2000})
            getOrderDetail()
        } else {
            layer.msg(data.msg)
        }
    }
    return web.doAjax(root.orderInter.order_cancelRefundItem, 'post', params, successData, 1)
}
/*订单备注编辑*/
var oldVal = "";
function reason(data) {
    switch (data) {
        /*订单状态*/
        case 0:
            return "";
        case 10:
            return "商品质量问题";
        case 11:
            return "其它原因";
        case 12:
            return "收到商品与网站展示不符(颜色、图片、规格、产地及详情描述)";
        case 13:
            return "客户原因无理由退货";
        case 14:
            return "资质问题";
        case 20:
            return "大小/型号与商品描述不符";
        case 30:
            return "颜色/图案与商品描述不符";
        case 40:
            return "功能/效果与商品描述不符";
        case 50:
            return "商城发错货";
        case 51:
            return "客户订购错误/计划有变";
        case 52:
            return "价格高";
        case 54:
            return "支付问题";
        case 55:
            return "重复下单";
        case 56:
            return "暂时不需要了";
        case 57:
            return "订单信息有误";
        case 58:
            return "无货";
        case 59:
            return "其他";
        case 60:
            return "少件/漏发";
        case 61:
            return "商品质量问题";
        case 62:
            return "价格错误";
        case 70:
            return "多买/买错不想要了";
        case 80:
            return "到货物流破损";
        case 90:
            return "发票问题";
        case 100:
            return "未按约定时间送货";
        case 101:
            return "客户原因未收货";
        case 102:
            return "其它原因";
        case 103:
            return "现场无人收货";
        case 104:
            return "工地验收不合格";
        case 105:
            return "下错订单";
        case 106:
            return "送错货";
        case 107:
            return "客户地址留错";
        case 108:
            return "物流送货延迟";
        case 140:
            return "资质问题";
        case 53:
            return "货未集齐";
        default:
            return ""
    }
}
function reason2(data) {
    switch (data) {
        /*订单状态*/
        case 0:
            return "";
        case 10:
            return "商品质量问题";
        case 20:
            return "大小/型号与商品描述不符";
        case 30:
            return "颜色/图案与商品描述不符";
        case 40:
            return "功能/效果与商品描述不符";
        case 50:
            return "商城发错货";
        case 60:
            return "商品发错/少件/漏发";
        case 70:
            return "多买/买错不想要了";
        case 80:
            return "到货物流破损";
        case 90:
            return "发票问题";
        case 100:
            return "未按约定时间送货";
        case 110:
            return "其它原因";
        case 120:
            return "收到商品与网站展示不符";
        case 130:
            return "无理由退货";
        case 140:
            return "资质问题";
        default:
            return "";
    }
}
//编辑
function toEdit() {
    oldVal = $(".orderRemark textarea").val();
    $("#isSaveFalse").hide();
    $("#isSaveTrue").show();
    $(".orderRemark textarea").removeAttr("readonly");
}
// 取消
function toCancle() {
    $(".orderRemark textarea").val(oldVal);
    $("#isSaveFalse").show();
    $("#isSaveTrue").hide();
    $(".orderRemark textarea").attr("readonly", "readonly");
}

// 保存
function remarkToSave() {
    $('#isSaveFalse').show();
    $('#isSaveTrue').hide();
    $(".orderRemark textarea").attr("readonly", "readonly");
    //退货单备注保存
    var params = {
        refund_id: $('#askFor-code').html(),
        operate_userid: loginData.user.user_ID,
        operate_username: loginData.user.name,
        refund_remark: $('#remark').val(),
    }
    var successCallBack = function (data) {
        if (data.errorCode == 0) {
            layer.msg('保存成功', {time: 2000})
        } else {
            layer.msg(data.msg, {time: 2000})
        }
    }
    return web.doAjax(root.orderInter.order_saveRefundRemark, 'post', params, successCallBack, 1)
}
/*改变图片大小*/
function setSize(img) {
    var width = img.offsetWidth;
    if (width == 100) {
        img.style.width = 300 + 'px';
        img.style.height = 300 + 'px';
    } else {
        img.style.width = 100 + 'px';
        img.style.height = 100 + 'px';
    }
}

/*详细信息编辑*/
function requireUpdataInter(updataData) {
    $.ajax({
        contentType: "application/json",
        type: "POST",
        url: root.orderInter.order_edit,
        cache: false, //禁用缓存
        dataType: "json",
        data: updataData,
        success: function (result) {
            if (result.code == 0) {
                $('#addressInpBox').hide();
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest);
        }
    });
}

function updataDisplay(ids) {
    $(ids).css({
        display: "block",
    })
}

// 跳转商品详情页
function goToGoodsDetail(title, url, sku_Id) {
    var index = layer.open({
        type: 2,
        title: title,
        content: url + '?sku_Id=' + sku_Id
    });
    layer.full(index);
}

function checkOrder(title, url) {
    var orderid = $('#order-code').html();
    sessionStorage.setItem("orderId", orderid);
    var index = layer.open({
        type: 2,
        title: title,
        content: url
    });
    layer.full(index);
}

//服务费计算
$('#serviceMoneyInput').keyup(function () {
    var returnSkuMoney = parseFloat($('#returnSkuMoney').html());
    var deliveryMoney = parseFloat($('#shipping_fee').html());
    var return_freight = parseFloat($('#return_freight').html());
    var serviceMax = (returnSkuMoney + deliveryMoney) * 0.15;
    if ($(this).val() > round2(serviceMax, 2)) {
        layer.msg('服务费不能大于退货商品开票金额的15%', {time: 2000})
    } else {
        $('#returnMoney').html(parseFloat(returnSkuMoney + return_freight - $(this).val() - $('#deliveryMoneyInput').val()).toFixed(2));
    }
})

function Taxdeduction() {
    var returnSkuMoney = parseFloat($('#returnSkuMoney').html());
    var deliveryMoney = parseFloat($('#shipping_fee').html());
    var return_freight = parseFloat($('#return_freight').html());
    var serviceMax = (returnSkuMoney + deliveryMoney) * 0.15;
    $('#serviceMoneyInput').val(round2(serviceMax, 2));
    $('#returnMoney').html(parseFloat(returnSkuMoney + return_freight - serviceMax - $('#deliveryMoneyInput').val()).toFixed(2));
}

//限制输入框只能输入两位小数
function clearNoNum(obj) {
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
    if (obj.value.indexOf(".") < 0 && obj.value != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        obj.value = parseFloat(obj.value);
    }
    if (!obj.value || obj.value == '0' || obj.value == '0.0' || obj.value == '0.00') {
        //   alert('退款金额不能为空');
        return;
    }
    //  正常得话继续调后端接口
}

function round2(number, fractionDigits) {
    with (Math) {
        return round(number * pow(10, fractionDigits)) / pow(10, fractionDigits);
    }
}

$('#deliveryMoneyInput').keyup(function () {
    var returnSkuMoney = parseFloat($('#returnSkuMoney').html());
    var return_freight = parseFloat($('#return_freight').html());
    var deliveryMax = (returnSkuMoney - $('#serviceMoneyInput').val())
    if ($(this).val() > deliveryMax) {
        layer.msg('服务费加运费不能大于退货商品支付金额', {time: 2000})
    } else {
        $('#returnMoney').html(parseFloat(returnSkuMoney + return_freight - $(this).val() - $('#serviceMoneyInput').val()).toFixed(2));
    }
})
/*设置是否退运费*/
var isSetReturnFreight = 0; // 0-不退运费；1-退运费
function setReturnFreight(flag) {
    var returnSkuMoney = $('#returnSkuMoney').html(); // 退货商品金额
    var return_freight = 0; // 要退运费金额
    if (flag == 1) {
        return_freight = $("#shipping_fee").html();
        $("#return_freight").html(return_freight)
        isSetReturnFreight = 1;
        $(".tui").attr("onclick", "return false;");
        $(".tui").css({"color": "grey"});
        $(".notui").css({"color": "#1e79e9"});
        $(".notui").attr("onclick", "setReturnFreight(2)");
        yunfie = 1
    } else {
        $("#return_freight").html(return_freight)
        isSetReturnFreight = 0;
        $(".notui").attr("onclick", "return false;");
        $(".notui").css({"color": "grey"});
        $(".tui").css({"color": "#1e79e9"});
        $(".tui").attr("onclick", "setReturnFreight(1)");
    }
    $('#returnMoney').html((Number(returnSkuMoney) + Number(return_freight) - Number($('#serviceMoneyInput').val()) - Number($('#deliveryMoneyInput').val())).toFixed(2));
}

//关联订单号
function relationOrder() {
    $("#relationOrdertable").find("tbody").html("")
    $.ajax({
        type: "POST",
        url: root.orderInter.queryReturnLinkOrder,
        cache: false,  //禁用缓存F
        dataType: "json",
        data: {
            "customerId": customerId,// 客户id
        },
        success: function (result) {
            var commodityInformation = ""
            var datas = result.data
            var hierarchy = 0
            if (datas != "" && datas != null) {
                $("#relationOrder").modal("show")
                $.each(datas, function (k, v) {
                    hierarchy++;
                    var orderStatus = ""
                    if (v.orderStatus == 30) {
                        orderStatus = "待配货"
                    } else if (v.orderStatus == 40) {
                        orderStatus = "待出库"
                    }
                    if (v.orderStatus == 50) {
                        orderStatus = "待发货"
                    }
                    if (v.orderStatus == 60) {
                        orderStatus = "待收货"
                    }
                    var isReturn = ""
                    if (v.isReturn == 1) {
                        isReturn = "否"
                    } else {
                        isReturn = "是"
                    }
                    var detailAddress = v.provinceName + v.cityName + v.areaName + v.townName + v.detailAddress
                    var detailAddress2 = v.provinceName + v.cityName + v.areaName + v.detailAddress
                    if ($("#orderidall").html() != "") {
                        if ($("#orderidall").html() == v.orderId) {
                            commodityInformation += '<tr class="commodityInformations" >' +
                                '<td class="biaoge1-1"><input class="radio" type="radio" name="relations" value="' + v.orderId + '"  checked="checked"><span >' + hierarchy + '</span></td>' +
                                '<td class="biaoge1-1"><span >' + v.orderId + '</span></td>' +
                                '<td class="biaoge1-2"><span >' + orderStatus + '</span></td>' +
                                '<td class="biaoge1-3"><span >' + isReturn + '</span></td>' +
                                '<td class="biaoge1-3"><span >' + detailAddress + '</span></td>' +
                                '<td  style="display: none"><span class="biaoge1-6">' + detailAddress2 + '</span></td>' +
                                '</tr>';
                        } else {
                            commodityInformation += '<tr class="commodityInformations" >' +
                                '<td class="biaoge1-1"><input class="radio" type="radio" name="relations" value="' + v.orderId + '" ><span >' + hierarchy + '</span></td>' +
                                '<td class="biaoge1-1"><span >' + v.orderId + '</span></td>' +
                                '<td class="biaoge1-2"><span >' + orderStatus + '</span></td>' +
                                '<td class="biaoge1-3"><span >' + isReturn + '</span></td>' +
                                '<td class="biaoge1-3"><span >' + detailAddress + '</span></td>' +
                                '<td  style="display: none"><span class="biaoge1-6">' + detailAddress2 + '</span></td>' +
                                '</tr>';
                        }

                    } else {
                        commodityInformation += '<tr class="commodityInformations" >' +
                            '<td class="biaoge1-1"><input class="radio" type="radio" name="relations" value="' + v.orderId + '" ><span >' + hierarchy + '</span></td>' +
                            '<td class="biaoge1-1"><span >' + v.orderId + '</span></td>' +
                            '<td class="biaoge1-2"><span >' + orderStatus + '</span></td>' +
                            '<td class="biaoge1-3"><span >' + isReturn + '</span></td>' +
                            '<td class="biaoge1-3"><span >' + detailAddress + '</span></td>' +
                            '<td style="display: none"><span class="biaoge1-6">' + detailAddress2 + '</span></td>' +
                            '</tr>';
                    }
                })
                $("#relationOrdertable").find("tbody").html($(commodityInformation));
            } else {
                $("#relationOrder").modal("hide");
                layer.msg('没有可关联的订单请更换返回方式', {time: 2000})
            }
        }
    });
}

//返回方式
function returnsReasonall() {
    displayornot()
    if ($("#returnsReason").val() == 10) {
        var orderDetails = orderDetail.orderExt
        $("#getProvinces option:selected").val("")
        $("#getProvinces option:selected").html("")
        $("#getProvinces").attr("disabled", false)

        $("#getCitys option:selected").val("")
        $("#getCitys option:selected").html("")
        $("#getCitys").attr("disabled", false)

        $("#getAreas option:selected").val("")
        $("#getAreas option:selected").html("")
        $("#getAreas").attr("disabled", false)

        $("#getCountys option:selected").val("")
        $("#getCountys option:selected").html("")
        $("#getCountys").attr("disabled", false)

        $("#detail_address").val(orderDetails.receiver_province_name + "" + orderDetails.receiver_city_name + "" + orderDetails.receiver_area_name + "" + orderDetails.receiver_town_name + "" + orderDetails.receiver_detail_address);
        $("#detail_address").attr("disabled", false)
        $("#received_name").val(orderDetail.listAddressReceiver[0].receiver_name)

        $("#received_name").attr("disabled", false)

        $("#received_telephone").val(orderDetail.listAddressReceiver[0].mobile)

        $("#received_telephone").attr("disabled", false)
    } else {
        //自行寄回
        $.ajax({
            type: "get",
            url: root.publics.pcqueryAllReturnAddress,
            cache: false,  //禁用缓存
            dataType: "json",
            data: {},
            success: function (data) {
                var houseList = data.data
                for (var i = 0; i < houseList.length; i++) {
                    if (orderDetail.orderRefund.warehouse_id == houseList[i].warehouseCode) {

                        $("#getProvinces option:selected").val(houseList[i].provinceCode)
                        $("#getProvinces option:selected").html(houseList[i].provinceName)
                        $("#getProvinces").attr("disabled", "disabled")

                        $("#getCitys option:selected").val(houseList[i].cityCode)
                        $("#getCitys option:selected").html(houseList[i].cityName)
                        $("#getCitys").attr("disabled", "disabled")

                        $("#getAreas option:selected").val(houseList[i].districtCode)
                        $("#getAreas option:selected").html(houseList[i].districtName)
                        $("#getAreas").attr("disabled", "disabled")
                        $("#getCountys option:selected").val(houseList[i].streetCode)
                        $("#getCountys option:selected").html(houseList[i].streetName)
                        $("#getCountys").attr("disabled", "disabled")
                        $("#detail_address").val(houseList[i].detailAddress)
                        $("#detail_address").attr("disabled", "disabled")
                        $("#received_name").val(houseList[i].contactPerson)
                        $("#received_name").attr("disabled", "disabled")

                        $("#received_telephone").val(houseList[i].contactPhone)
                        $("#received_telephone").attr("disabled", "disabled")
                    }
                }
            },
            error: function () {
                layer.msg('失败！', {time: 2000})
            }
        });
    }
}
/**
 * 根据订单的经纬度定位四级地址
 * @param returnOrderId 订单号
 */
function queryDetailAddress(returnOrderId){
    var params = {
        orderId: returnOrderId
    }
    var successCallBack = function(data){
            if(data.errorCode == 0){
                var townCode = data.data.townCode;
                if(!townCode){
                    $("#getCountys option:selected").val("")
                    $("#getCountys option:selected").html("")
                    $("#getCountys").attr("disabled", "disabled")
                }else{
                    $("#getCountys option:selected").val(data.data.townCode)
                    $("#getCountys option:selected").html(data.data.town)
                    $("#getCountys").attr("disabled", "disabled")
                }
            }else{
                layer.msg(data.msg, {time: 2000});
            }
    }
    return web.doAjax(root.dockingplatform.queryDetailAddress, 'post', params, successCallBack)
}
//关联订单号取消
function relationOrdercancel() {
    $("#relationOrder").modal("hide")
}

//是否展示下次送货订单号
function displayornot() {
    if ($("#returnsReason").val() == 10) {
        $("#relationOrders").show();
    } else {
        $("#relationOrders").hide();
    }
}

//关联订单号确定
function relationOrderdetermine() {
    if ($("input[name='relations']:checked").val() == undefined) {
        layer.msg('请关联下次送货订单号', {time: 2000})
    } else {
        var detail_address = $("#getProvinces option:selected").html() + $("#getCitys option:selected").html() + $("#getAreas option:selected").html() + $("#getCountys option:selected").html() + $("#detail_address").val()//收货地址
        var relationss = $("input[name='relations']:checked").parent().parent().find(".biaoge1-6")
        if ($(relationss).html() != detail_address) {
            var cu = layer.confirm('<span>当前关联订单收货地址同退货订单收货地址不同确定要关联么？</span>', {
                title: '提示',
                btn: ['确认', '取消']
            }, function (index) {
                $("#relationOrder").modal("hide")
                $("#orderidall").html($("input[name='relations']:checked").val())
                layer.close(cu);
            }, function () {
                layer.close(cu);
            });
        } else {
            $("#relationOrder").modal("hide")
            $("#orderidall").html($("input[name='relations']:checked").val())
        }
    }
}

//关联单据
function relatedDocuments() {
    $.ajax({
        url: root.dockingplatform.queryRelatedRefundOrder,
        contentType: "application/json",
        type: "POST",
        cache: false, //禁用缓存
        dataType: "json",
        data: JSON.stringify({
            "orderId": returnOrderId,// 订单编号
            "refundId": returnId // 退货单编号
        }),
        success: function (result) {
            if (result.errorCode == "0") {
                $("#relatedDocuments").modal("show")
                var data = result.data
                var relatedDocumentstable = ''
                for (var i = 0; i < data.length; i++) {
                    for (var f = 0; f < data[i].refundItemList.length; f++) {
                        if (f == 0) {
                            var sourceall = ""
                            if (data[i].source == 10) {
                                sourceall = "渠道发起"
                            } else if (data[i].source == 20) {
                                sourceall = "线下发起"
                            }
                            relatedDocumentstable += '<tr><td><input type="checkbox" class="relatedDocumentsid" data-id="' + data[i].refundId + '"></td><td>' + data[i].refundId + '</td><td>' + data[i].orderId + '</td><td>' + data[i].channelOrderId + '</td><td>' + sourceall + '</td><td>' + data[i].refundAt + '</td>';
                            relatedDocumentstable += '<td>' + data[i].refundItemList[f].productCode + '</td><td>' + data[i].refundItemList[f].productName + '</td><td>' + data[i].refundItemList[f].skuInfo + '</td><td>' + data[i].refundItemList[f].color + '</td><td>' + data[i].refundItemList[f].refundCount + '</td>'
                            relatedDocumentstable += '</tr>';
                        } else {
                            relatedDocumentstable += '<tr><td></td><td></td><td></td><td></td><td></td><td></td>';
                            relatedDocumentstable += '<td>' + data[i].refundItemList[f].productCode + '</td><td>' + data[i].refundItemList[f].productName + '</td><td>' + data[i].refundItemList[f].skuInfo + '</td><td>' + data[i].refundItemList[f].color + '</td><td>' + data[i].refundItemList[f].refundCount + '</td>'
                            relatedDocumentstable += '</tr>';
                        }
                    }
                }
                $("#relatedDocumentstable").html(relatedDocumentstable)
            } else {
                layer.msg(result.msg, {icon: 5, time: 1000});
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.msg('网络错误');
        }
    });
}

//取消关联单据
function relatedDocumentscancel() {
    $("#relatedDocuments").modal("hide")
}

//确认关联
function confirmconnection() {
    var orderId = []
    $.each($(".relatedDocumentsid"), function (index, item) {
        if ($(this).is(":checked")) {
            var orders = item.getAttribute('data-id')
            orderId.push(orders)
        }
    })
    /* 这部分是否需要对orderId进行为空判断*/
    confirmRelated(orderId)
}
//  确认关联接口
function confirmRelated(orderId){
    var params = {
        sourceRefundId: returnId,
        relatedRefundIdList: orderId,
        operateUserId: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
        operateUserName: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
    }
    var successCallBack = function(data){
            if(data.errorCode == 0){
                layer.msg("关联成功", {icon: 6, time: 1000}, function () {
                    $("#relatedDocuments").modal("hide")
                    location.replace(location.href)
                });
            }else{
                layer.msg(data.msg, {icon: 5, time: 1000});
            }
    }
     return web.doAjax(root.dockingplatform.confirmRelated, 'post', params, successCallBack, 1)
}